import { Component, Injector, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import { SeoModalComponent } from "@app/main/shared/seo/seo-modal.component";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { AppComponentBase } from "@shared/common/app-component-base";
import { FieldType, MenuInfoConfig, MenuInfoServiceProxy, MenuItemDto } from "@shared/service-proxies/service-proxies";
import { TreeNode } from "primeng/api";
import { ImageTextModalComponent } from "../shared/menuInfo/image-text-modal.component";
import { ImageTextService } from "../shared/menuInfo/imageText.service";
import { MenuExtendModalComponent } from "../shared/menuInfo/menu-extend-modal.component";
import { MenuInfoConfigModalComponent } from "../shared/menuInfo/menu-info-config-modal.component";
import { MenuExtensionInfoItem } from "./menu-extension-info-item";

@Component({
    templateUrl: "./menu-info.component.html",
    animations: [appModuleAnimation()]
})
export class MenuInfoComponent extends AppComponentBase implements OnInit {

    @ViewChild('seoModal', { static: true }) seoModal: SeoModalComponent;
    @ViewChild('extendedDataModal', { static: true }) extendedDataModal: MenuExtendModalComponent;
    @ViewChild('jsonEditorModal', { static: true }) jsonEditorModal: MenuInfoConfigModalComponent;
    @ViewChild('imageTextModal', { static: true }) imageTextModal: ImageTextModalComponent;
    
    menuTreeData: TreeNode<MenuExtensionInfoItem>[] = []
    cols: any[];
    kind: number;

    defaultConfig: MenuInfoConfig;

    hasConfigPermission = this.permission.isGranted('Pages.Tenant.MenuInfo.Config')

    constructor(
        injector: Injector,
        private _imageTextService: ImageTextService,
        private _activatedRoute: ActivatedRoute,
        private _menuInfoServiceProxy: MenuInfoServiceProxy
    ) {
        super(injector);
    }

    ngOnInit() {
        this._activatedRoute.params.subscribe((params: Params) => {
            this.kind = Number(params['kind']);

            this.getDefaultConfig(() => {
                this.getMenuInfoData(this.kind);
            })

        });
        this.cols = [
            { field: 'localDisplayName', header: '栏目' }
        ];
    }

    goSeoModal(record: MenuExtensionInfoItem) {
        this.seoModal.show(record.id, record.auxiliaryId, record.displayName);
    }
    
    goImageTextModal(record: MenuExtensionInfoItem) {
        this.imageTextModal.show(record.menuExtensionConfig, record.id, record.auxiliaryId, record.displayName, record.permissions);
    }

    goExtendedDataModal(record: MenuExtensionInfoItem) {
        let formName = record.menuExtensionConfig.extended.formName;
        formName = KTUtil.toCamelCase(formName);
        let form = record.menuExtensionConfig.forms[formName];
        this.extendedDataModal.show(record.auxiliaryId, record.id, record.permissions, form, ImageTextService.extendKey, null);
    }

    goConfigModal(record: MenuExtensionInfoItem) {
        this.jsonEditorModal.show(record.auxiliaryId);
    }

    reloadPage(){
        this.getMenuInfoData(this.kind);
    }

    private getMenuInfoData(kind: number) {
        this._menuInfoServiceProxy.getMenuTree(kind).subscribe(result => {
            let treeNodes: TreeNode<MenuExtensionInfoItem>[] = []
            this.getMenuTreeData(result, null, treeNodes);
            this.menuTreeData = treeNodes;
        });
    }


    private getDefaultConfig(initTreeCall: { (): void }) {
        let result = this._imageTextService.getDefaultConfig();

        this.defaultConfig = result;
        initTreeCall && initTreeCall();
    }


    private getConfig(configStr: string): MenuInfoConfig {
        let config: MenuInfoConfig;
        if (configStr) {
            try {
                var data = KTUtil.jsonToCamelCase(JSON.parse(configStr), (key,val)=>{
                    if(key === "fieldType"){
                        return FieldType[val];
                    }
                    return val;
                });

                config = new MenuInfoConfig(data);
            } catch (e) {
                config = this.defaultConfig;
            }
        } else {
            config = this.defaultConfig;
        }

        return config;
    }


    private getMenuTreeData(menuItems: MenuItemDto[], parnentId: string, menuTreeDatas: TreeNode<MenuExtensionInfoItem>[]) {
        for (const item of menuItems) {
            if (item.parentId == parnentId) {
                let ids = menuTreeDatas.map(item => item.data.id);
                if (ids.indexOf(item.id) < 0) {
                    let newTreeNode: TreeNode<MenuExtensionInfoItem> = {};
                    newTreeNode.data = this.transformMenuInfoDto(item);
                    newTreeNode.children = [];
                    menuTreeDatas.push(newTreeNode);
                    this.getMenuTreeData(menuItems, item.id, newTreeNode.children);
                }
            }
        }
    }

    private transformMenuInfoDto(item: MenuItemDto): MenuExtensionInfoItem {
        let menuExtensionItem = new MenuExtensionInfoItem();
        menuExtensionItem.auxiliaryId = item.auxiliaryId;
        menuExtensionItem.parentId = item.parentId;
        menuExtensionItem.code = item.code;
        menuExtensionItem.displayName = item.displayName;
        menuExtensionItem.order = item.order;
        menuExtensionItem.isActive = item.isActive;
        menuExtensionItem.localDisplayName = item.localDisplayName;
        menuExtensionItem.permissions = item.permissions;
        menuExtensionItem.id = item.id;
        menuExtensionItem.menuExtensionConfig = this.getConfig(item.menuInfoConfig);

        return menuExtensionItem;
    }
}
